from django import template
from django.db.models.fields import Field
from django.db.models import Model
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape


from tppt.lib import actions 

register = template.Library()

@register.filter
def attr(value, name):
	try:
		if isinstance(name, Field):
			name=name.name
		if hasattr(value, name):
			return getattr(value, name)
		elif name in value:
			return value[name]
		else:
			return '#INVALID ATTRIBUTE:%s#' % name
	except:
		if settings.DEBUG:
			return '#ERROR WHILE GETTING ATTRIBUTE %s#' % name
		else:
			return ''

@register.filter
@template.defaultfilters.stringfilter
def truncate(value,maxsize,stopper = '...'):
	""" truncates a string to a given maximum
		size and appends the stopper if needed """
	if value.find('<') != -1:
		return value
	from tppt.lib.utils import human_trunc
	return human_trunc(value, maxsize, stopper)

@register.filter
def actions_details(object):
	from tppt.lib.actions import get_actions_details
	return get_actions_details(object)

@register.filter
def humanize(object, autoescape=None):
	if autoescape:
		esc = conditional_escape
	else:
		esc = lambda x: x
	
	
	if isinstance(object, Field):
		return object.verbose_name.capitalize()
	elif isinstance(object, type) and issubclass(object, Model):
		return object._meta.verbose_name_plural.capitalize()
	elif isinstance(object, Model):
		url=actions.get_action_url('details', object)
		res='<a href="%s">%s</a>' % (url, esc(str(object)))
		return mark_safe(res)
	elif object.__class__.__name__=='ManyRelatedManager':
		#ManyRelatedManager cannot be imported so we're doing that dirty test here.
		return mark_safe(humanize_m2m_field(object))
	return str(object)
humanize.needs_autoescape = True


def humanize_m2m_field(mgr):
	if mgr.count()==0:
		return '[]'
	
	preview_cnt=2
	
	entities=[]
	for ent in mgr.iterator():
		entities.append(ent)
		if len(entities)>=preview_cnt:
			break
	
	links=[humanize(ent) for ent in entities]

	reduce_fn=lambda a, b: "%s%s, " % (a,  b)
	links_str=reduce(reduce_fn,  links[:-1],  '')+links[-1]
	
	if len(entities)<mgr.count():
		links_str+=', ...';
	
	src_entity=mgr.instance
	src_field_name=mgr.instance.__class__.get_m2m_field_name_from_mgr(mgr).name
	query_set=mgr.model.objects.all().filter_m2m(src_entity, src_field_name)
	
	all_url=actions.get_action_url('index', query_set)
	all_link='<a href="%s">(all)</a>' % all_url
		
	return "[%s %s]" % (links_str, all_link) 
